<template>
  <div class="page-content default-radius">
    <div class="header">
      <h3 class="title">{{ contentConfig.header.title ?? '数据列表' }}</h3>
      <el-button v-if="canCreate" type="primary" @click="handleCreatePageRecord">{{
        contentConfig.header.btnText ?? '新增数据'
      }}</el-button>
    </div>
    <div class="tip" v-if="!canQuery">
      <p>抱歉当前账户没有权限查看该数据列表，特殊需要请联系管理员！</p>
    </div>
    <div class="table" v-if="canQuery">
      <el-table
        :data="statePageList"
        :border="true"
        style="width: 100%"
        v-bind="contentConfig?.childrenTree ?? ''"
      >
        <template v-for="item in contentConfig.tableData" :key="item.prop">
          <!-- 当前这一列为时间类型 -->
          <el-table-column
            v-if="item.type === 'timer'"
            :align="item.align ?? 'center'"
            v-bind="item"
          >
            <template #default="scope">
              {{ utcFormat(scope.row[item.prop]) }}
            </template>
          </el-table-column>
          <!-- 当前这一列为操作类型 -->
          <el-table-column
            v-else-if="item.type === 'handler'"
            :align="item.align ?? 'center'"
            v-bind="item"
          >
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                icon="EditPen"
                link
                @click="handleEditPageRecord(scope.row)"
                :disabled="!canUpdate"
              >
                编辑
              </el-button>
              <el-popconfirm
                confirm-button-text="删除"
                confirm-button-type="danger"
                cancel-button-text="取消"
                icon="InfoFilled"
                icon-color="#f56c6c"
                title="您确定要删除吗？"
                @confirm="handleDeletePageRecord(scope.row.id)"
              >
                <template #reference>
                  <el-button type="danger" size="small" icon="Delete" link :disabled="!canDelete">
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="item.type === 'custom'"
            :align="item.align ?? 'center'"
            v-bind="item"
          >
            <template #default="scope">
              <!-- 利用作用域插槽，将上层作用域插槽中的数据传回去 -->
              <slot :name="item.slotName" :row="scope.row"></slot>
            </template>
          </el-table-column>
          <el-table-column v-else :align="item.align ?? 'center'" v-bind="item" />
        </template>
      </el-table>
    </div>
    <div class="footer" v-if="canQuery">
      <el-pagination
        v-if="!contentConfig.notPagination"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="statePageTotalCount ? Number(statePageTotalCount) : 0"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { useSystemStore } from '@/store/mian/system';
import { ref } from 'vue';
import { storeToRefs } from 'pinia';
import { utcFormat } from '@/utils/format-util';
import type { IContentProps } from '@/components/page-content/type';
import usePermissions from '@/hooks/usePermissions';

const props = defineProps<IContentProps>();
const systemStore = useSystemStore();
const { statePageList, statePageTotalCount } = storeToRefs(systemStore);

const currentPage = ref(1);
const pageSize = ref(10);

// 定义传递给父组件的事件
const emits = defineEmits(['createRecord', 'editRecord']);

// 0.获取是否有对应的增删改查的权限
const canCreate = usePermissions(props.contentConfig.pageName + ':create');
const canUpdate = usePermissions(props.contentConfig.pageName + ':update');
const canDelete = usePermissions(props.contentConfig.pageName + ':delete');
const canQuery = usePermissions(props.contentConfig.pageName + ':query');

// 在修改删除添加之后让currentPage为1
systemStore.$onAction(({ name, after }) => {
  after(() => {
    if (
      name === 'deleteRecordByIdAction' ||
      name === 'createRecordAction' ||
      name === 'editRecordByIdAction'
    ) {
      currentPage.value = 1;
    }
  });
});

// 1.获取表格数据
fetchPageListData();

/**
 * @function handleSizeChange 改变每页表格条数，表格会自动修改绑定的pageSize属性
 */
function handleSizeChange() {
  fetchPageListData();
}

/**
 * @function handleCurrentChange 改变当前页码，表格会自动修改绑定的currentPage属性
 */
function handleCurrentChange() {
  fetchPageListData();
}

/**
 * @function fetchPageListData 获取当前组件的表格数据
 * @param formData
 */
function fetchPageListData(formData: any = {}) {
  if (!canQuery) return;
  const size = pageSize.value;
  const offset = (currentPage.value - 1) * size;
  const queryInfo = { ...formData, offset, size };
  systemStore.fetchPageListDataAction(props.contentConfig.pageName, queryInfo);
}

/**
 * @function handleEditPageRecord 编辑表格中的某一行
 * @param itemData
 */
function handleEditPageRecord(itemData: any) {
  emits('editRecord', itemData);
}

/**
 * @function handleDeletePageRecord 删除表格中的某一行
 * @param id
 */
function handleDeletePageRecord(id: number) {
  systemStore.deleteRecordByIdAction(props.contentConfig.pageName, id);
  currentPage.value = 1;
}

/**
 * @function handleCreatePageRecord 新建表格中的某一行
 */
function handleCreatePageRecord() {
  emits('createRecord');
}

/** 对外暴露的方法 */
defineExpose({
  // 允许父组件调用刷新数据
  fetchPageListData
});
</script>

<style scoped lang="scss">
.page-content {
  background-color: #ffffff;
  padding: 20px;
  margin-top: 20px;
  margin-bottom: 40px;

  .header {
    display: flex;
    height: 45px;
    padding: 0 5px;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 20px;
      font-weight: 700;
    }

    .handler {
      align-items: center;
    }
  }
  .tip {
    padding: 10px 0;
    text-align: center;
    color: #b0b0b0;
  }

  .table {
    :deep(.el-table__cell) {
      padding: 14px 0;
    }
  }

  .footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 15px;
    padding-right: 20px;
  }
}
</style>
